from api.extension import db

import datetime

###################### 基础公共模型类定义 ######################

# 定义一些公共的方法，如to_dict()；
# 因为jsonify()只能序列化基本的数据类型如字典、列表、字符串、数字等，模型实例不是JSON可序列化的
class FormatMixin(object):
     
     def to_dict(self):
        res = dict()
        obj = getattr(self, "__mapper__")
        for key in obj.c.keys():
            if key in {'password', '_password', 'secret', '_secret'}:
                continue
            if key.startswith('_'):
                key = key[1:]
            if not isinstance(getattr(self, key), (datetime.date, datetime.time, datetime.datetime)):
                res[key] = getattr(self, key)
            else: 
                res[key] = str(getattr(self, key))
        return res
    

# 审计字段
class AuditMixin(object):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    deleted = db.Column(db.Boolean, default=False)
    create_by = db.Column(db.String(64), comment="创建人")
    create_time = db.Column(db.DateTime, default=lambda: datetime.datetime.now())
    update_by = db.Column(db.String(64), comment="修改人")
    update_time = db.Column(db.DateTime, onupdate=lambda: datetime.datetime.now())


# 基础模型对象基类
class Model(AuditMixin, FormatMixin, db.Model):
    __abstract__ = True

